package com.qxsx.midi.activity.me;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.activity.home.CourseDetailsActivity;
import com.qxsx.midi.activity.home.MusicDetailsActivity;
import com.qxsx.midi.adapter.MyOrderAdapter;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.model.Order;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.view.ZListView.ZListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;


public class MyOrderActivity extends BaseActivity implements OnClickListener {
    private CustomProgress customProgress;

    Button btnPayed;
    Button btnUnPayed;
    ZListView listView;
    private ArrayList<Order> allList = new ArrayList<>();
    private ArrayList<Order> lists;
    private MyOrderAdapter listAdapter;

    private int _page = 1; //   初始化页码为1
    private int _state = 0;//   初始化付款状态
    private static final int PAGESIZE = 10; //每页请求数量
    private String _userId;
    private String buy = "0";
    private final static int UPDATE_UI = 0;

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_UI:

                    _page = 1;
                    allList.clear();
                    listAdapter.RemoveAll();
                    loadData(_state, _page);

                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order);
        setTitle("我的订单");
        setNavBtn(R.mipmap.back, 0);
        findById();

    }

    private void findById() {

        btnPayed = (Button) findViewById(R.id.btn_payed);
        btnPayed.setOnClickListener(this);

        btnUnPayed = (Button) findViewById(R.id.btn_unpayed);
        btnUnPayed.setOnClickListener(this);

        listView = (ZListView) findViewById(R.id.item_list_my_order);

    }

    private void inItData() {

        _userId = (String) SPUtils.get(AppContext.getContext(), "user_id", "");
        lists = new ArrayList<>();
        listAdapter = new MyOrderAdapter(MyOrderActivity.this, lists, MyOrderActivity.this,mHandler);
        listView.setAdapter(listAdapter);
        onClick(btnUnPayed);

        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);

        listView.setXListViewListener(new ZListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        _page = 1;
                        allList.clear();
                        listAdapter.RemoveAll();
                        loadData(_state, _page);

                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        _page++;
                        loadData(_state, _page);
                    }
                }, 2000);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        inItData();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (allList.get(position - 1).get_type().equals("1")) {
                    Intent intent = new Intent();
                    intent.putExtra("id", allList.get(position - 1).get_matid());
                    intent.putExtra("type", allList.get(position - 1).get_type());
                    intent.putExtra("buy", buy);
                    intent.setClass(MyOrderActivity.this, MusicDetailsActivity.class);
                    startActivity(intent);

                } else {
                    Intent intent = new Intent();
                    intent.putExtra("id", allList.get(position - 1).get_matid());
                    intent.putExtra("buy", buy);
                    intent.setClass(MyOrderActivity.this, CourseDetailsActivity.class);
                    startActivity(intent);

                }

            }
        });

    }

    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_payed:
                btnPayed.setTextColor(getResources().getColor(R.color.text_black));
                btnUnPayed.setTextColor(getResources().getColor(R.color.text_grey));
                _state = 1;
                _page = 1;
                buy = "1";
                allList.clear();
                listAdapter.RemoveAll();
                loadData(_state, _page);
                break;
            case R.id.btn_unpayed:
                btnUnPayed.setTextColor(getResources().getColor(R.color.text_black));
                btnPayed.setTextColor(getResources().getColor(R.color.text_grey));
                _state = 0;
                _page = 1;
                buy = "0";
                allList.clear();
                listAdapter.RemoveAll();
                loadData(_state, _page);
                break;


        }
    }

    /**
     * state 是指付款状态 订单状态[0=未付款,1=已付款]
     *
     * @param state
     */
    public void loadData(final int state, int page) {

        customProgress = CustomProgress.show(MyOrderActivity.this, "请稍后....", true, null);
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("user_id", _userId);
            object.put("order_state_code", state + "");
            object.put("nowpage", page + "");
            object.put("pagesize", PAGESIZE + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("8021", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {

                    try {
                        lists = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            Order order = new Order();
                            order.set_id(object.getString("order_id"));
                            order.set_code(object.getString("orde_code"));
                            order.set_time(object.getString("create_time"));
                            order.set_matid(object.getString("material_id"));
                            order.set_name(object.getString("name"));
                            order.set_num(object.getString("grade_num"));
                            order.set_price(object.getString("price"));
                            order.set_desc(object.getString("introduction"));
                            order.set_state(state);
                            order.set_type(object.getString("order_type"));
                            order.setMajor_id(object.getString("major_id"));
                            lists.add(order);
                            allList.add(order);
                        }
                        if (state==0){
                            listAdapter.AddData(lists,true);
                        }else{
                            listAdapter.AddData(lists,false);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("code", code.toString());
                    Log.e("message", message.toString());
                }
                listView.stopRefresh();
                listView.stopLoadMore();
                customProgress.dismiss();
            }
        });


    }

}
